package com.lfsenior.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by dlupan on 2018/10/31
 */
public class QueueReceivers {
    // TCP 地址
    public static final String BROKER_URL="tcp://localhost:61616";
    // 目标
    public static final String DESTINATION="QUEUE-QUEUE";

    public static void run() throws Exception{
        // 创建连接工厂
        QueueConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);
        // 创建连接
        QueueConnection connection = factory.createQueueConnection();
        // 启动连接
        connection.start();
        // 创建Session
        QueueSession session = connection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
        // 创建队列
        Queue queue = session.createQueue(DESTINATION);
        // 创建接受者
        QueueReceiver receiver = session.createReceiver(queue);

        /*while (true){
            Message message = receiver.receive(1000);
            if(message!=null){
                MapMessage map = (MapMessage) message;
                System.out.println(map.getLong("time")+"接收#"+map.getString("text"));
            }else{
                break;
            }
        }*/
        receiver.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                MapMessage map = (MapMessage) message;
                try {
                    System.out.println(map.getLong("time")+"接收#"+map.getString("text"));

                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });

        // 休眠100s
        Thread.sleep(1000);

        // 提交会话
        session.commit();
        session.close();
        connection.close();
    }

    public static void main(String[] args) throws Exception{
        QueueReceivers.run();
    }
}
